using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
    //========================================================================
    
    ///<Player data>
        public static int m_score = 0;                                    //分数
		public static int m_highScore = 0;								//分数最高纪录
        public static int m_birdsLeft = 5;                                      //剩下的鱼
        public const int MAX_FISH = 999;										//可拥有的最多的鱼

		public static bool m_isInfiniteBirds = false;										//无限子弹
		const float m_MAX_ITEM_USE_TIME = 10F;
		public static float m_start_useItemTime = 0;
		float m_useItemTimeLeft = 0;
		public static int m_itemBomb = 0;										//拥有的炸弹

		const int MAX_BOMB = 3;
    ///</Player data>

    ///<GUI>
		public GUISkin menuGuiSkin;
		public GUISkin gameSkin;

		public struct ScreenBorder
		{
			public float leftBorder;
			public float rightBorder;
			public float upBorder;
			public float downBorder;
		} ;
		public static ScreenBorder screenBorder= new ScreenBorder() ;

        int screenWidth;                                                 //width of screen
        int screenHeight;                                                //height.

		public Texture2D imgIntroduce;									//Introduce of game.

		public Texture2D imgBt_BombItem;									//The bomb button to be show.	
		public Texture2D imgLb_ItemInfinite;							//无限子弹时间
		public Texture2D imgBox_background;

        public Texture2D imgEnergy;                                                 //Texture of energy
		public Texture2D imgBirds;											//Texture for birds GUI.

		protected Texture2D imgBt_Sound;									//Display on gui
		public Texture2D imgBt_SoundOn;										//To be used by imgBt_Sound;
		public Texture2D imgBt_SoundOff;

        Rect rectScore;                                                         //The position of GUI: Money
    ///</GUI>

    ///<GAME>
        public enum GameStatus{START, INTRODUCE , PLAYING , PAUSE , GAME_OVER};                  //Enum the status of game
        public static GameStatus gameStatus = GameStatus.START;                                    //Current game status.

        /// <Touch manager>
		//protected Vector2[] m_touchPos = new Vector2[5];                                        //The record of finger pos first touched.
		//protected GameObject[] touchedObject = new GameObject[5];                      //Obj controlling.
		public GameObject go_birdHouse;
		Vector3 v3_birdHouse;
        public float distanceFromCamera = 10;                                                       //The distance between camera and the game layer.
        public GameObject[] m_birdObjPrefab = new GameObject[3];                    //The prefab of fish.
        /// </Touch manager>
        
        /// <Energy>
        public float[] m_energy = new float[5];                                                        //How powerful the fish was.
        public float MAX_ENERGY = 2;                                                           //The max energy it will got.
        public int[,] m_energyPos = new int[5,2];
        /// </Energy>
        
        
    ///</GAME>
    
    
    //========================================================================
	void Awake()
	{
		Application.targetFrameRate = 60;
	}
    void Start () {
		
        //Get screen info:
        screenHeight = Screen.height;
        screenWidth = Screen.width;
        rectScore = new Rect(Screen.width *0.8F, 10, 0.2F*screenWidth, 0.08F*screenHeight);
        menuGuiSkin.button.fontSize = (int)(0.06F * screenHeight);
        menuGuiSkin.box.fontSize = (int)(0.05F * screenHeight);
        menuGuiSkin.label.fontSize = (int)(0.06F*screenHeight);
        gameSkin.label.fontSize = (int)(0.05F*screenHeight);

        int rectBombSize = (int)(0.1F * screenWidth);
        rectBombBtn = new Rect(0, rectBombSize, rectBombSize, rectBombSize);

		///<获取屏幕左右边界的世界坐标>
		Vector3 tmpV3= TransformScreenToWorld(new Vector3(0,0,0));
		screenBorder.leftBorder = tmpV3.x;
		screenBorder.downBorder = tmpV3.y;

		tmpV3 = TransformScreenToWorld(new Vector3(Screen.width , Screen.height , 0));
		screenBorder.rightBorder = tmpV3.x;
		screenBorder.upBorder = tmpV3.y;
        //Debug.Log("screen left:" + screenBorder.leftBorder + " r:" + screenBorder.rightBorder + " up:" + screenBorder.upBorder + " down:" + screenBorder.downBorder);
		///</获取屏幕左右边界的世界坐标>

        //Set the game status first.
        gameStatus = GameStatus.START;
		Time.timeScale = 0;

		/// Player setting:获取小鸟的发射出生点
		v3_birdHouse = go_birdHouse.transform.position;
		

		///<EnemySpawn>
		//设置敌人的重生点
		Vector3 posEnemySpawn = TransformScreenToWorld(new Vector3(0 , screenHeight- 20 , 0));
																//屏幕的一半对应的世界坐标，即为生成敌人时候的上下距离的差值
		float genPosDelta = posEnemySpawn.y;
		GameObject tmpTransform =  GameObject.FindGameObjectWithTag("EnemySpawn");
		tmpTransform.GetComponent<EnemyBirdsSpawn>().SetMyPosition(new Vector3(screenBorder.rightBorder+4 , 0 ,0),genPosDelta);
		///</EnemySpawn>
		
		

	}

    Rect rectBombBtn;
    void OnGUI()
    {
		if (gameStatus != GameStatus.PLAYING)
			GUI.skin = menuGuiSkin;
		else
			GUI.skin = gameSkin;

        switch(gameStatus)
        {
            case GameStatus.PLAYING:
                //Draw the gaming GUI:
                GUI.Label(rectScore, "Score:"+ m_score);
                GUI.DrawTexture(new Rect(0, 10, 0.06F * screenHeight, 0.06F * screenHeight), (m_isInfiniteBirds ? imgLb_ItemInfinite : imgBirds));
                GUI.Label(new Rect(0.06F * screenHeight, 8, 0.2F*screenWidth, 0.08F * screenHeight), " x " + (m_isInfiniteBirds ? (int)(m_useItemTimeLeft * 100) : m_birdsLeft));

				//Show the item if can be used:
				if (m_itemBomb > 0)
				{
                    int rectBombSize = (int)(0.1F * screenWidth);
                    GUI.Label(new Rect(rectBombSize, rectBombSize*1.3F, rectBombSize, rectBombSize), " x " + m_itemBomb);
					//GUI.DrawTexture(new Rect(rectBombBtn.x,rectBombBtn.y,rectBombBtn.width,rectBombBtn.height),imgBt_BombItem);
                    if (GUI.Button(rectBombBtn, imgBt_BombItem))
					{
						UseBomb();
					}
				}

                break;

            case GameStatus.START:
                //Draw the start menu:
                GUI.Box(new Rect(0,0,screenWidth,screenHeight),"START");
                int startX = (int)(0.35F * screenWidth);
                 int rectW = (int)(0.3F * screenWidth);
                int rectH = (int)(0.42F * rectW);
                if(GUI.Button(new Rect(startX,0.25F*screenHeight,rectW,rectH ),"Start"))
                {
                    RestartGame();
                }
                if(GUI.Button(new Rect(startX,0.542F*screenHeight,rectW,rectH ),"Quit"))
                {
                    Application.Quit();
                }
				if (GUI.Button(new Rect(10 , 10 , 0.125F*screenWidth , 0.08F*screenHeight) , "?"))
				{
					gameStatus = GameStatus.INTRODUCE;
				}

				//Icon : Music
				bool bgmPlay = GUI.Toggle(new Rect(10 , 0.91F*screenHeight, 0.125F*screenWidth , 0.09F*screenHeight) , SoundManager.Instance.IsPlayingBGM() , imgBt_Sound);
				
				if (bgmPlay)
				{
					SoundManager.Instance.TurnOnMusic();
					imgBt_Sound = imgBt_SoundOn;
				}
				else
				{
					SoundManager.Instance.TurnOffMusic();
					imgBt_Sound = imgBt_SoundOff;
				}
                break;

            case GameStatus.PAUSE:
                GUI.Box(new Rect(0,0,screenWidth,screenHeight),"PAUSE");

                startX = (int)(0.35F * screenWidth);
                rectW = (int)(0.3F * screenWidth);
                rectH = (int)(0.42F * rectW);
                if(GUI.Button(new Rect(startX,0.29F*screenHeight,rectW,rectH),"Continue"))
                {
                    gameStatus = GameStatus.PLAYING;
                    //freeze the time:
                    Time.timeScale = 1;
                }
                if(GUI.Button(new Rect(startX,0.542F*screenHeight,rectW,rectH ),"Quit"))
                {
                    Application.Quit();
                }

				bgmPlay = GUI.Toggle(new Rect(10 , 0.92F*screenHeight , 0.125F*screenWidth, 0.08F*screenHeight) , SoundManager.Instance.IsPlayingBGM() , imgBt_Sound);
				
				if (bgmPlay)
				{
					SoundManager.Instance.TurnOnMusic();
					imgBt_Sound = imgBt_SoundOn;
				}
				else
				{
					SoundManager.Instance.TurnOffMusic();
					imgBt_Sound = imgBt_SoundOff;
				}
                break;

            case GameStatus.GAME_OVER:
                GUI.Box(new Rect(0,0,screenWidth,screenHeight),"GAME OVER");
                startX = (int)(0.35F * screenWidth);
                rectW = (int)(0.3F * screenWidth);
                rectH = (int)(0.15F * screenHeight);

                GUI.DrawTexture(new Rect(0.1F*screenWidth,0.08F*screenHeight,0.8F*screenWidth,0.84F*screenHeight),imgBox_background);
				GUI.Label(new Rect(startX, 0.25F*screenHeight , 0.3F*screenWidth , 0.1F*screenHeight) , "Score:" + m_score);
				GUI.Label(new Rect(startX, 0.35F*screenHeight , 0.35F*screenWidth, 0.1F*screenHeight) , "Record:" + m_highScore);
                if(GUI.Button(new Rect(startX,0.5F*screenHeight,rectW,rectH ),"Restart"))
                {
                    RestartGame();
                }
                if(GUI.Button(new Rect(startX,0.7F*screenHeight,rectW,rectH ),"Quit"))
                {
                    Application.Quit();
                }
                break;

			case GameStatus.INTRODUCE:
				GUI.Box(new Rect(0 , 0 , screenWidth , screenHeight) , "INTRODUCE");

				GUI.DrawTexture(new Rect(screenWidth *0.125F , 0.08F*screenHeight, 0.75F*screenWidth, 0.84F*screenHeight) , imgIntroduce);
				
				
				if (GUI.Button(new Rect(10 , 10 , 0.125F*screenWidth ,0.083F*screenHeight) , "x"))
				{
					gameStatus = GameStatus.START;
				}
				break;
        }


        
    }
    void Update()
    {
        CheckGameStatus();

        if (gameStatus != GameStatus.PLAYING)
            return;
        #if (!UNITY_EDITOR && ( UNITY_IOS || UNITY_ANDROID))
                MobileCheckDrag();
        #else
                DesktopCheckDrag();
        #endif

       
    }

	void OnApplicationPause()
	{
		gameStatus = GameStatus.PAUSE;
	}

    private void CheckGameStatus()
    {

		#if ( !UNITY_IOS || UNITY_EDITOR)
		if (Input.GetKeyUp(KeyCode.Escape))
		{
			switch (gameStatus)
			{
			case GameStatus.PLAYING:
				//freeze the time:
				Time.timeScale = 0;
				gameStatus = GameStatus.PAUSE;
				break;
				
			case GameStatus.PAUSE:
				//Reset the time
				Time.timeScale = 1;
				gameStatus = GameStatus.PLAYING;
				break;
				
			case GameStatus.INTRODUCE:
				gameStatus = GameStatus.START;
				break;
				
			case GameStatus.GAME_OVER:
				Application.Quit();
				break;
			}
		}
		#endif
        
		if (m_birdsLeft <= 0)
		{
			m_birdsLeft = 0;

			if (GameObject.FindGameObjectWithTag("Player_Attack_Area") == null)
			{
				//If no fishes left, game over:
				Time.timeScale = 0;
				SetGameOver();
			}
		}

		//道具使用中的处理
		if (m_isInfiniteBirds)
		{
			if (Time.time - m_start_useItemTime > m_MAX_ITEM_USE_TIME)
			{
				m_start_useItemTime = 0;
				m_isInfiniteBirds = false;
			}

			m_useItemTimeLeft = m_start_useItemTime + m_MAX_ITEM_USE_TIME - Time.time;
		}
    }

    //**********************************************************************
    //					CheckDrag
    //
    //	You can only generate the fish on the area of pool.
    //**********************************************************************

    //----------------------------------
    //Mobile check drag
    //  MobileCheckDrag()
    //----------------------------------

	void MobileCheckDrag()
	{
		
		for (int i = 0 ; i < Input.touchCount ; i++)	//Travel the fingers' touch.
		{

			if (m_isInfiniteBirds || Input.touches[i].phase == TouchPhase.Began )								
			{
				//拥有无限鸟道具效果的情况下随意发射
				//没有道具效果的情况下，只能点击一个发射一个
				GenerateBird(Input.touches[i].position);
			}
			
		}
		
	}

	

    //----------------------------------
    //PC Check:
    //          DesktopCheckDrag()
    //----------------------------------

    void DesktopCheckDrag()
    {
		//	Note:
		//	When click the mouse, generate a rocket_bird from nest and launch it to the mouse position.

		if (Input.GetMouseButtonDown(0))
		{
			//鼠标位置就是目的地，以此发射小鸟
			GenerateBird( Input.mousePosition );

		}
    }

	private void GenerateBird(Vector2 touchPos)
	{
        //If is in illegal area, retun...For bomb button clicked.
        if (m_itemBomb > 0 && rectBombBtn.Contains(new Vector2(touchPos.x, screenHeight - touchPos.y)))
            return;
        

		//判断:1.是否还有可以发射的鸟		 2.是否是在按按钮
		//||touchPos.x < 32 && (touchPos.y > screenHeight - 84) && (touchPos.y <screenHeight - 52)
		if (m_birdsLeft <= 0)
			return;
		
		if (!m_isInfiniteBirds)
		{
			SubFish();
		}
		
		
		
		Vector3 tmpFlyDirection = new Vector3(touchPos.x ,
																			touchPos.y - screenHeight * 0.5F ,
																			0);
		tmpFlyDirection.Normalize();

		GameObject playerBird = (GameObject)Instantiate(m_birdObjPrefab[Random.Range(0 , m_birdObjPrefab.Length)] , v3_birdHouse , Quaternion.identity);
		playerBird.GetComponent<PlayerBirds>().SetFlyDirection(tmpFlyDirection);
		playerBird.transform.LookAt(tmpFlyDirection * 100);										//向量x10是因为之前被正交化了。
		SoundManager.Instance.PlayAudio(SoundManager.AUDIOTYPE.GENERATE_BIRD);
	}

    

    //**********************************************************************
    //                            Restart the game()
    //**********************************************************************
    protected void RestartGame()
    {
		//Destroy all fishs flying...
		GameObject[] gos = GameObject.FindGameObjectsWithTag("Player_Attack_Area");
		for (int i = 0 ; i < gos.Length ; i++)
		{
			Destroy(gos[i].gameObject);
		}

		//Destroy the enemy.
		gos = GameObject.FindGameObjectsWithTag("Enemy");
		for (int i = 0 ; i < gos.Length ; i++)
		{
			Destroy(gos[i].gameObject);
		}

		gos = GameObject.FindGameObjectsWithTag("Item");
		for (int i = 0 ; i < gos.Length ; i++)
		{
			Destroy(gos[i].gameObject);
		}

		//Destroy particle and text FX
		gos = GameObject.FindGameObjectsWithTag("FX_TEXT_PARTICLE");
		for (int i = 0 ; i < gos.Length ; i++)
		{
			Destroy(gos[i].gameObject);
		}
		
        m_birdsLeft = 15;
        m_score = 0;
		m_itemBomb = 0;
		m_isInfiniteBirds = false;
		m_start_useItemTime = 0;
		gameStatus = GameStatus.PLAYING;
		Time.timeScale = 1;

		EnemyBirdsSpawn.genTime = 0;

		//Play the sound to start:
		SoundManager.Instance.PlayAudio(SoundManager.AUDIOTYPE.START_GAME);
    }


    //**********************************************************************
    //                            Set Game over()
    //**********************************************************************
    public static void SetGameOver()
    {
		m_highScore = PlayerPrefs.GetInt("HIGHT_SCORE");

		if (m_score > m_highScore)
		{
			m_highScore = m_score;
			PlayerPrefs.SetInt("HIGHT_SCORE",m_highScore);
		}
        gameStatus = GameStatus.GAME_OVER;
    }

    //-----------------------
    //      IsPlaying()
    //-----------------------
    public static bool IsPlaying()
    {
        return gameStatus == GameStatus.PLAYING;
    }

    //-----------------------
    //      AddScore
    //-----------------------
    public static void AddScore(int val)
    {
        if(!GameManager.IsPlaying())
            return;
            
        m_score = m_score + val*100;
		AddFish();
    }

	//增加炸弹
	public static void AddBomb()
	{
		if (m_itemBomb >= MAX_BOMB)
			return;
		m_itemBomb++;
	}

	//使用炸弹
	public void UseBomb()
	{
		if (m_itemBomb <= 0)
			return;

		m_itemBomb--;

		//找到所有敌人，消灭它们
		GameObject[] gos = GameObject.FindGameObjectsWithTag("Enemy");
		for (int i = 0 ; i < gos.Length ; i++)
		{
			gos[i].GetComponent<Enemy>().DoExplode();
		}

	}

    /*
    public static void SubScore(int val)
    {
        if (!GameManager.IsPlaying())
            return;

        m_score = m_score - val;
        if( m_score <= 0 )
            m_score = 0;
    }
    */

    //-----------------------
    //      AddFish()
    //-----------------------
    public static void AddFish()
    {
        m_birdsLeft+=1;
        if (m_birdsLeft >= MAX_FISH)
            m_birdsLeft = MAX_FISH;
     
    }

    //-----------------------
    //      SubFish()
    //  if the fish was less 
    //than 0,then game over.
    //-----------------------
    public static void SubFish(int val = 1)
    {
        m_birdsLeft-=val ;
        if(m_birdsLeft <= 0)
        {
            m_birdsLeft = 0;
			if (val > 1)
			{
				SetGameOver();
			}
        }
    }

    //-----------------------
    //      GetFish()
    //  return the fish count.
    //-----------------------
    public static int GetFish()
    {
        return m_birdsLeft;
    }

    //--------------------------------
    //      TransformToWorld()
    //Translate the mouse pos to 
    //World.
    //--------------------------------
    public Vector3 TransformScreenToWorld(Vector3 tmp)
    {
        //tmp.x = tmp.x*0.5F / screenWidth ;
        //tmp.y = 0;
        //tmp.z = 0;

        tmp = Camera.main.ScreenToWorldPoint(new Vector3(tmp.x, tmp.y, distanceFromCamera));
        
        //print("After Mouse :" + tmp.x + " " + tmp.y);
        return tmp;
    }



	public static void UseItem(Item.ITEM_TYPE m_itemType)
	{
		if (m_itemType == Item.ITEM_TYPE.infinite_birds)
		{
			m_isInfiniteBirds = true;
			m_start_useItemTime = Time.time;
		}
	}
}
